<template>
  <view class="order-confirm">
    <!-- 添加加载状态显示 -->
    <view class="loading-state" v-if="isLoading">
      <text>加载中...</text>
    </view>
    
    <!-- 添加错误状态显示 -->
    <view class="error-state" v-if="hasError">
      <text>{{ errorMessage }}</text>
      <button @tap="reload" class="reload-btn">重新加载</button>
    </view>
    
    <!-- 原有内容在非加载和非错误状态下显示 -->
    <template v-if="!isLoading && !hasError">
      <!-- 收货地址 -->
      <view class="address-section">
        <view class="address-info" v-if="address && address.name" @tap="chooseAddress">
          <view class="user-info">
            <text class="name">{{ address.name }}</text>
            <text class="phone">{{ address.phone }}</text>
          </view>
          <view class="address-detail">
            <text class="tag" v-if="address.tag">{{ address.tag }}</text>
            <text class="detail">
              {{ getAddressText(address) }}
            </text>
          </view>
          <text class="arrow">></text>
        </view>
        <view class="no-address" v-else>
          <button class="add-address-btn" @tap="chooseAddress">添加新地址</button>
        </view>
      </view>

      <!-- 药品列表 -->
      <view class="medicine-list">
        <view class="list-header">
          <view class="header-left">
            <text>药品信息</text>
            <text class="total-count" v-if="orderInfo.totalCount > 0">共{{ orderInfo.totalCount }}件</text>
          </view>
          <text class="specification" v-if="orderInfo.spec">{{ orderInfo.spec }}</text>
        </view>
        <view class="medicine-item" v-for="(item, index) in orderItems" :key="index">
          <image :src="item.imageUrl || '/static/medicine-default.png'" mode="aspectFill" class="medicine-image"></image>
          <view class="medicine-info">
            <text class="medicine-name">{{ item.medicineName }}</text>
            <view class="medicine-details">
              <text class="medicine-spec">{{ item.specification || '规格信息' }}</text>
              <text class="medicine-dosage" v-if="item.dosageForm">{{ item.dosageForm }}</text>
            </view>
            <view class="price-quantity">
              <text class="price">¥{{ item.price.toFixed(2) }}</text>
              <view class="item-quantity">
                <text class="quantity">x{{ item.quantity }}</text>
                <text class="item-total">小计: ¥{{ (item.price * item.quantity).toFixed(2) }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 配送方式 -->
      <view class="delivery-section">
        <view class="section-item">
          <text class="label">配送方式</text>
          <view class="value">
            <text>快递配送</text>
          </view>
        </view>
        <view class="section-item">
          <text class="label">配送时间</text>
          <view class="value">
            <text>预计3天内送达</text>
          </view>
        </view>
      </view>

      <!-- 支付方式 -->
      <view class="payment-section">
        <view class="section-header">
          <text>支付方式</text>
        </view>
        <view class="payment-options">
          <view 
            class="payment-option" 
            v-for="(option, index) in paymentOptions" 
            :key="index"
            @tap="selectPayment(index)"
            :class="{ active: selectedPayment === index }"
          >
            <image :src="option.icon" mode="aspectFit" class="payment-icon"></image>
            <text class="payment-name">{{ option.name }}</text>
            <view class="checkbox" :class="{ checked: selectedPayment === index }"></view>
          </view>
        </view>
      </view>

      <!-- 订单金额 -->
      <view class="price-section">
        <view class="price-item">
          <text class="label">商品金额</text>
          <text class="value">¥{{ totalPrice }}</text>
        </view>
        <view class="price-item">
          <text class="label">运费</text>
          <text class="value">¥{{ deliveryFee }}</text>
        </view>
        <view class="price-item total">
          <text class="label">实付金额</text>
          <text class="value">¥{{ actualPayment }}</text>
        </view>
      </view>

      <!-- 底部支付栏 -->
      <view class="pay-bar">
        <view class="total-price">
          <text>合计：</text>
          <text class="price">¥{{ actualPayment }}</text>
        </view>
        <button 
          class="pay-btn" 
          @tap="submitOrder" 
          :disabled="isLoading"
          :class="{ 'loading': isLoading }"
        >
          {{ isLoading ? '提交中...' : '提交订单' }}
        </button>
      </view>
    </template>

    <!-- 调试工具区域，仅开发使用 -->
    <view class="debug-section" v-if="isDevelopment">
      <view class="debug-title">开发测试工具</view>
      <view class="debug-buttons">
        <button class="debug-btn" @tap="testNavigateToAddressList">测试地址列表导航</button>
        <button class="debug-btn" @tap="testDirectAddAddress">测试添加地址导航</button>
        <button class="debug-btn alt" @tap="alternativeNavigateToAddressList">替代地址导航</button>
        <button class="debug-btn alt" @tap="openAddressListAsNewPage">新页面打开地址</button>
        <button class="debug-btn" @tap="checkLocalStorage">检查本地存储</button>
        <button class="debug-btn" @tap="checkPageConfiguration">检查页面配置</button>
        <button class="debug-btn" @tap="fixNavigationIssue">修复导航问题</button>
        <button class="debug-btn danger" @tap="clearLocalCache">清理缓存数据</button>
      </view>
    </view>

    <!-- 支付二维码弹窗 -->
    <view v-if="showQRCode" class="qrcode-popup-overlay" @click="closeQRCode">
      <view class="qrcode-popup" @click.stop>
        <view class="popup-header">
          <text class="popup-title">使用微信扫码支付</text>
          <text class="close-btn" @click="closeQRCode">×</text>
        </view>
        <view class="qrcode-content">
          <view v-if="qrCodeUrl" class="qrcode-wrapper">
            <image 
              :src="qrCodeUrl" 
              mode="aspectFit" 
              class="qrcode-image"
              @error="handleQRCodeError"
              @load="handleQRCodeLoad"
            ></image>
            <text class="price">¥{{ actualPayment }}</text>
          </view>
          <view v-else class="loading-wrapper">
            <text class="loading">正在生成支付二维码...</text>
          </view>
        </view>
        <view class="qrcode-footer">
          <text class="tip">请使用微信扫一扫完成支付</text>
          <text class="order-number">订单号：{{ currentOrderId }}</text>
          <view class="qrcode-buttons">
            <button class="qr-btn cancel" @tap="closeQRCode">取消支付</button>
            <button class="qr-btn confirm" @tap="confirmPayment">已完成支付</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 导入必要的API和工具
import checkLogin from '@/mixins/checkLogin'
import { addressApi } from '@/api/address'
import { orderApi } from '@/api/order'
import { cartApi } from '@/api/cart'
import auth from '@/utils/auth'  // 引入认证工具类
import { orderMedicineApi } from '@/api/orderMedicine'

export default {
  mixins: [checkLogin],
  data() {
    return {
      orderItems: [],
      address: null,
      paymentOptions: [
        { name: '微信支付', icon: '/static/wxpay.png', value: 'WECHAT' },
        { name: '银行卡支付', icon: '/static/bankpay.png', value: 'CARD' }
      ],
      selectedPayment: 0,
      deliveryFee: '10.00',
      isLoading: false,
      orderInfo: {
        spec: '',
        totalCount: 0
      },
      hasError: false,
      errorMessage: '',
      paymentStatusTimer: null,
      qrCodeUrl: '',
      showQRCode: false,
      currentOrderId: null,
      loadingStates: {
        submitting: false,
        paying: false
      },
      errorStates: {
        orderSubmit: false,
        payment: false
      },
      retryCount: 0,
      maxRetries: 3,
      outTradeNo: '', // 商户订单号
    }
  },
  
  computed: {
    // 商品总价 - 修复价格计算方法
    totalPrice() {
      if (!this.orderItems || this.orderItems.length === 0) {
        return '0.00';
      }
      
      let total = 0;
      this.orderItems.forEach(item => {
        // 确保使用数字类型进行计算
        const price = typeof item.price === 'string' ? parseFloat(item.price) : item.price || 0;
        const quantity = typeof item.quantity === 'string' ? parseInt(item.quantity) : item.quantity || 0;
        
        // 单个商品总价
        const itemTotal = price * quantity;
        total += itemTotal;
        
        // 可选：调试输出
        console.log(`商品: ${item.medicineName}, 单价: ${price}, 数量: ${quantity}, 小计: ${itemTotal}`);
      });
      
      // 返回保留两位小数的金额
      return total.toFixed(2);
    },
    
    // 实付金额 - 保持计算一致性
    actualPayment() {
      // 转换为数字确保计算准确
      const totalPrice = parseFloat(this.totalPrice) || 0;
      const deliveryFee = parseFloat(this.deliveryFee) || 0;
      return (totalPrice + deliveryFee).toFixed(2);
    }
  },
  
  onLoad(options) {
    // 添加错误处理和日志
    console.log('订单确认页面加载', options);
    
    try {
      // 初始化默认地址
      this.initDefaultAddress();
      
      // 加载订单数据
      this.loadOrderItems();
      
      // 获取默认地址
      this.getDefaultAddress();
      
    } catch (error) {
      console.error('页面初始化失败:', error);
      uni.showToast({
        title: '页面加载失败，请重试',
        icon: 'none'
      });
    }
  },
  
  onShow() {
    console.log('订单确认页面显示');
    try {
      // 刷新地址数据
      const refreshAddress = uni.getStorageSync('refreshAddress');
      if (refreshAddress) {
        this.getDefaultAddress();
        uni.removeStorageSync('refreshAddress');
      }
      
      // 检查订单数据
      if (!this.orderItems || this.orderItems.length === 0) {
        this.loadOrderItems();
      }
      
      // 检查并修复地址字段
      this.fixAddressFields();
      
    } catch (error) {
      console.error('页面显示时刷新数据失败:', error);
    }
  },
  
  methods: {
    // 修改 loadOrderItems 方法
    loadOrderItems() {
      try {
        console.log('开始加载订单项');
        let tempItems = uni.getStorageSync('checkoutItems');
        console.log('从存储获取的原始订单数据:', tempItems);
        
        // 处理数据格式
        let items = tempItems;
        if (typeof tempItems === 'string') {
          try {
            items = JSON.parse(tempItems);
          } catch (e) {
            console.error('解析订单数据失败:', e);
          }
        }
        
        // 如果没有数据，尝试从备用存储获取
        if (!items || !Array.isArray(items) || items.length === 0) {
          items = uni.getStorageSync('tempOrderItems');
          console.log('从备用存储获取数据:', items);
        }
        
        // 如果仍然没有数据，显示错误并返回
        if (!items || !Array.isArray(items) || items.length === 0) {
          throw new Error('未找到有效的订单数据');
        }
        
        // 处理订单项数据，确保保留原始数量
        this.orderItems = items.map(item => {
          // 获取原始数量，确保是数字类型
          const originalQuantity = parseInt(item.quantity) || 1;
          console.log(`商品 ${item.medicineName} 的原始数量:`, originalQuantity);
          
          const processedItem = {
            id: item.id || item.medicineId,
            medicineId: item.medicineId,
            medicineName: item.medicineName,
            imageUrl: item.imageUrl || '/static/medicine-default.png',
            price: parseFloat(item.price) || 0,
            quantity: originalQuantity, // 使用原始数量
            specification: item.specification || '',
            dosageForm: item.dosageForm || ''
          };
          
          // 计算商品小计
          processedItem.itemTotal = (processedItem.price * processedItem.quantity).toFixed(2);
          
          console.log(`处理后的商品数据:`, processedItem);
          return processedItem;
        });
        
        console.log('最终处理后的订单项:', this.orderItems);
        
        // 更新订单信息
        this.updateOrderInfo();
        
      } catch (error) {
        console.error('加载订单项失败:', error);
        uni.showToast({
          title: error.message || '加载订单数据失败',
          icon: 'none',
          duration: 2000
        });
        
        // 延迟返回上一页
        setTimeout(() => {
          uni.navigateBack();
        }, 2000);
      }
    },
    
    // 添加更新订单信息的方法
    updateOrderInfo() {
      let totalCount = 0;
      let specInfo = '';
      
      this.orderItems.forEach(item => {
        totalCount += parseInt(item.quantity) || 0;
        if (item.specification && !specInfo) {
          specInfo = item.specification;
        }
      });
      
      this.orderInfo.totalCount = totalCount;
      this.orderInfo.spec = specInfo;
      
      // 强制更新视图
      this.$forceUpdate();
    },
    
    // 获取默认地址 - 改进版
    async getDefaultAddress() {
      try {
        // 获取用户标识
        const userId = this.getUserIdentifier();
        
        if (!userId) {
          uni.showToast({
            title: '未检测到登录信息',
            icon: 'none'
          });
          
          // 使用默认地址
          this.useDefaultAddressFromUserInfo();
          return;
        }
        
        // 首先尝试获取本地存储中的选择地址
        const selectedAddress = uni.getStorageSync('selectedAddress');
        if (selectedAddress) {
          console.log('使用已选择的地址:', selectedAddress);
          this.address = selectedAddress;
          // 使用后清除
          uni.removeStorageSync('selectedAddress');
          return;
        }
        
        // 尝试获取接口数据
        try {
          const res = await addressApi.getDefaultAddress(userId);
          
          if (res.code === 200 && res.data) {
            this.address = res.data;
            console.log('成功获取默认地址');
            return;
          }
          
          // 如果没有默认地址，获取地址列表第一个
          const listRes = await addressApi.getAddressList(userId);
          
          if (listRes.code === 200 && listRes.data && listRes.data.length > 0) {
            this.address = listRes.data[0];
            console.log('使用地址列表中的第一个地址');
            return;
          }
          
          // 找不到地址，使用默认值
          this.useDefaultAddressFromUserInfo();
          
        } catch (error) {
          console.error('获取地址API失败:', error);
          this.useDefaultAddressFromUserInfo();
        }
      } catch (error) {
        console.error('地址获取过程失败:', error);
        this.useDefaultAddressFromUserInfo();
      }
    },
    
    // 使用用户信息生成默认地址
    useDefaultAddressFromUserInfo() {
      console.log('使用默认地址');
      const userInfo = uni.getStorageSync('userInfo') || {};
      
      this.address = {
        addressId: Date.now(),
        name: userInfo.username || '用户',
        phone: userInfo.phone || '13260193128',
        provinceName: '广东省',
        cityName: '深圳市',
        districtName: '南山区',
        detail: '科技园南路XX号XX大厦',
        tag: '公司',
        isDefault: true
      };
    },
    
    // 选择地址 - 改进版
    chooseAddress() {
      try {
        console.log('开始选择地址流程');
        
        // 保存当前订单信息，以便返回时恢复
        uni.setStorageSync('tempOrderItems', this.orderItems);
        console.log('已保存订单项到本地存储');
        
        // 检查页面是否在pages.json中注册
        const pages = getCurrentPages();
        console.log('当前页面栈:', pages.map(p => p.route));
        
        // 添加调试信息
        console.log('准备跳转到地址列表页面');
        
        // 直接跳转到地址列表页面，确保参数正确
        uni.navigateTo({
          url: '/pages/address/address-list?select=true',
          success: () => {
            console.log('成功跳转到地址选择页面');
          },
          fail: (err) => {
            console.error('跳转地址选择页面失败:', err);
            
            // 检查失败原因并提供更多调试信息
            if (err.errMsg) {
              console.error('错误信息:', err.errMsg);
            }
            
            // 尝试使用不同的跳转方式
            console.log('尝试用redirectTo跳转');
            uni.redirectTo({
              url: '/pages/address/address-list?select=true',
              success: () => {
                console.log('redirectTo跳转成功');
              },
              fail: (redirectErr) => {
                console.error('redirectTo也失败:', redirectErr);
                
                // 显示用户友好的错误提示，并提供选项
                uni.showModal({
                  title: '提示',
                  content: '地址选择页面跳转失败，是否添加新地址？',
                  confirmText: '添加地址',
                  cancelText: '取消',
                  success: (res) => {
                    if (res.confirm) {
                      // 尝试直接跳转到地址添加页
                      uni.navigateTo({
                        url: '/pages/address/address-add',
                        fail: (addErr) => {
                          console.error('跳转添加地址页面也失败:', addErr);
                          // 如果添加页面也无法跳转，使用自动创建地址的方式
                          this.createDefaultAddress();
                        }
                      });
                    }
                  }
                });
              }
            });
          }
        });
      } catch (error) {
        console.error('选择地址操作失败:', error);
        this.handleAddressNavError();
      }
    },
    
    // 添加一个处理地址导航错误的方法
    handleAddressNavError() {
      // 获取当前登录用户信息
      const userInfo = uni.getStorageSync('userInfo') || {};
      
      // 显示错误提示
      uni.showModal({
        title: '地址管理',
        content: '无法打开地址页面，您可以在订单页面直接使用默认地址',
        confirmText: '使用默认地址',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 使用用户信息创建一个默认地址
            this.createDefaultAddress();
          }
        }
      });
    },

    // 创建默认地址方法
    createDefaultAddress() {
      // 获取当前登录用户信息
      const userInfo = uni.getStorageSync('userInfo') || {};
      
      // 使用用户信息构建一个默认地址
      const defaultAddress = {
        addressId: Date.now(), // 使用时间戳作为临时ID
        name: userInfo.username || '用户',
        phone: userInfo.phone || '13260193128', // 使用登录用户的手机号
        provinceName: '广东省',
        cityName: '深圳市',
        districtName: '南山区',
        detail: '科技园南路XX号XX大厦',
        tag: '公司',
        isDefault: true
      };
      
      // 保存这个地址作为临时选中地址
      uni.setStorageSync('selectedAddress', defaultAddress);
      uni.setStorageSync('refreshAddress', true);
      
      // 更新当前页面的地址
      this.address = defaultAddress;
      
      // 显示成功消息
      uni.showToast({
        title: '已设置默认地址',
        icon: 'success'
      });
    },
    
    // 选择支付方式
    selectPayment(index) {
      this.selectedPayment = index;
    },
    
    // 替换原有的 getUserIdentifier 方法
    getUserIdentifier() {
      const userId = auth.getUserIdentifier();
      if (!userId) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
      }
      return userId;
    },

   // 修改 submitOrder 方法
async submitOrder() {
  if (this.loadingStates.submitting) return;
  
  try {
    // 重置错误状态
    this.errorStates.orderSubmit = false;
    this.errorStates.payment = false;
    
    // 验证订单数据
    if (!this.validateOrderData()) {
      return;
    }
    
    // 获取用户ID
    const userId = this.getUserIdentifier();
    if (!userId) {
      throw new Error('请先登录');
    }
    
    // 设置加载状态
    this.loadingStates.submitting = true;
    uni.showLoading({
      title: '提交订单中...',
      mask: true
    });
    
    // 构建订单数据
    const orderData = {
      userId,
      receiverName: this.address.name,
      receiverPhone: this.address.phone,
      receiverAddress: this.getFullAddress(),
      paymentType: this.paymentOptions[this.selectedPayment].value,
      paymentName: this.paymentOptions[this.selectedPayment].name,
      deliveryFee: Number(this.deliveryFee),
      totalAmount: Number(this.totalPrice),
      actualPayment: Number(this.actualPayment),
      orderItems: this.orderItems.map(item => ({
        medicineId: item.medicineId,
        medicineName: item.medicineName,
        specification: item.specification || '',
        dosageForm: item.dosageForm || '',
        price: Number(item.price),
        quantity: Number(item.quantity),
        imageUrl: item.imageUrl || ''
      }))
    };
    
    // 创建订单
    const orderRes = await orderMedicineApi.createOrder(orderData);
    console.log('订单创建响应:', orderRes);
    
    if (orderRes.code !== 200 || !orderRes.data) {
      throw new Error(orderRes.msg || '创建订单失败');
    }
    
    // 保存订单信息
    this.currentOrderId = orderRes.data.orderId;
    this.outTradeNo = orderRes.data.outTradeNo;
    this.qrCodeUrl = orderRes.data.qrCodeImage;
    
    // 显示支付二维码
    this.showQRCode = true;
    
    // 开始检查支付状态
    this.startPaymentStatusCheck();
    
  } catch (error) {
    console.error('订单提交失败:', error);
    this.handleOrderSubmitError(error);
  } finally {
    this.loadingStates.submitting = false;
    uni.hideLoading();
  }
},

    // 修改支付状态检查方法
    async startPaymentStatusCheck() {
      if (!this.outTradeNo) {
        console.error('缺少商户订单号，无法检查支付状态');
        return;
      }
      
      this.clearPaymentStatusPolling();
      
      let checkCount = 0;
      const maxChecks = 60; // 3分钟 (3秒一次查询)
      
      const checkStatus = async () => {
        try {
          checkCount++;
          
          if (checkCount >= maxChecks) {
            this.clearPaymentStatusPolling();
            this.handlePayTimeout();
            return;
          }
          
          const res = await orderMedicineApi.checkPayStatus({
            outTradeNo: this.outTradeNo
          });
          console.log('支付状态查询结果:', res);
          
          if (res.code === 200) {
            switch(res.data) {
              case 'SUCCESS':
                this.handlePaymentSuccess();
                return;
              case 'TIMEOUT':
              case 'CLOSED':
                this.clearPaymentStatusPolling();
                this.handlePayTimeout();
                return;
              case 'PAYERROR':
                this.clearPaymentStatusPolling();
                this.handlePaymentError();
                return;
              case 'NOTPAY':
                // 继续轮询
                break;
              default:
                console.warn('未知的支付状态:', res.data);
                break;
            }
          }
          
          // 继续轮询
          this.paymentStatusTimer = setTimeout(checkStatus, 3000);
          
        } catch (error) {
          console.error('查询支付状态出错:', error);
          this.paymentStatusTimer = setTimeout(checkStatus, 3000);
        }
      };
      
      // 开始检查
      checkStatus();
    },

    // 添加支付错误处理方法
    handlePaymentError() {
      uni.showModal({
        title: '支付失败',
        content: '支付过程中出现错误，是否重试？',
        confirmText: '重试',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.retryPayment();
          } else {
            this.closeQRCode();
          }
        }
      });
    },

    // 修改重试支付方法
    async retryPayment() {
      try {
        uni.showLoading({
          title: '重新获取支付信息...',
          mask: true
        });
        
        const payRes = await orderMedicineApi.payOrder({
          orderId: this.currentOrderId,
          paymentType: this.paymentOptions[this.selectedPayment].value,
          totalFee: Math.round(Number(this.actualPayment) * 100).toString()
        });
        
        if (payRes.code === 200 && payRes.data) {
          this.outTradeNo = payRes.data.outTradeNo;
          this.qrCodeUrl = payRes.data.qrCodeImage;
          this.startPaymentStatusCheck();
        } else {
          throw new Error(payRes.msg || '获取支付二维码失败');
        }
      } catch (error) {
        console.error('重试支付失败:', error);
        uni.showToast({
          title: '重试失败，请稍后再试',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 验证订单数据
    validateOrderData() {
      // Check order items
      if (!this.orderItems || this.orderItems.length === 0) {
        uni.showToast({
          title: '订单商品不能为空',
          icon: 'none'
        });
        return false;
      }
      
      // Validate address
      if (!this.address) {
        uni.showToast({
          title: '请选择收货地址',
          icon: 'none'
        });
        return false;
      }
      
      // Check address completeness
      const fullAddress = this.getFullAddress();
      if (!fullAddress) {
        uni.showToast({
          title: '收货地址不完整，请重新选择',
          icon: 'none'
        });
        return false;
      }
      
      // Check payment method
      if (typeof this.selectedPayment !== 'number' || !this.paymentOptions[this.selectedPayment]) {
        uni.showToast({
          title: '请选择支付方式',
          icon: 'none'
        });
        return false;
      }
      
      return true;
    },
    
    // 初始化默认地址
    initDefaultAddress() {
      // 在本地存储中设置一个默认地址数据
      const defaultAddress = {
        addressId: 1,
        name: '张三',
        phone: '138****1234',
        provinceName: '广东省',
        cityName: '深圳市',
        districtName: '南山区',
        detail: '科技园南路XX号XX大厦',
        tag: '公司',
        isDefault: true
      };
      
      // 存储到本地，以便在API调用失败时使用
      uni.setStorageSync('defaultAddress', defaultAddress);
      
      return defaultAddress;
    },
    
    // 添加地址数据检查方法
    checkAddressData() {
      console.log('当前地址数据检查:');
      console.log('this.address:', this.address);
      
      if (!this.address) {
        console.error('地址对象为空!');
        return false;
      }
      
      // 检查关键字段
      const requiredFields = ['name', 'phone', 'provinceName', 'cityName', 'districtName', 'detail'];
      const missingFields = requiredFields.filter(field => !this.address[field]);
      
      if (missingFields.length > 0) {
        console.error('地址缺少必要字段:', missingFields);
        return false;
      }
      
      console.log('地址数据完整');
      return true;
    },

    // 检查本地缓存数据，用于调试
    checkLocalStorage() {
      try {
        console.log("====== 本地缓存调试信息 ======");
        const storageKeys = ['checkoutItems', 'tempOrderItems', 'token', 'userInfo', 'defaultAddress'];
        
        storageKeys.forEach(key => {
          const value = uni.getStorageSync(key);
          console.log(`${key}:`, value ? (typeof value === 'string' ? value : JSON.stringify(value)) : '未设置');
        });
        
        console.log("============================");
      } catch (error) {
        console.error('检查本地缓存失败:', error);
      }
    },

    // 清除本地缓存
    clearLocalCache() {
      uni.showModal({
        title: '清除缓存',
        content: '确定要清除订单相关缓存吗？这可能有助于解决数据问题。',
        success: (res) => {
          if (res.confirm) {
            // 只清除订单相关缓存，保留登录信息
            uni.removeStorageSync('checkoutItems');
            uni.removeStorageSync('tempOrderItems');
            uni.removeStorageSync('refreshAddress');
            
            uni.showToast({
              title: '缓存已清除',
              icon: 'success'
            });
            
            // 返回上一页
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          }
        }
      });
    },

    // 检查并修复地址字段
    fixAddressFields() {
      if (!this.address) return;
      
      console.log('修复前的地址对象:', JSON.stringify(this.address));
      
      // 确保字段名称一致
      if (!this.address.provinceName && this.address.province) {
        this.address.provinceName = this.address.province;
      }
      if (!this.address.cityName && this.address.city) {
        this.address.cityName = this.address.city;
      }
      if (!this.address.districtName && this.address.district) {
        this.address.districtName = this.address.district;
      }
      
      console.log('修复后的地址对象:', JSON.stringify(this.address));
    },

    // 获取地址文本
    getAddressText(address) {
      let text = '';
      if (address.provinceName) text += address.provinceName + ' ';
      if (address.cityName) text += address.cityName + ' ';
      if (address.districtName) text += address.districtName + ' ';
      if (address.detail) text += address.detail;
      return text.trim();
    },

    // 添加加载状态显示
    showLoadingState() {
      this.isLoading = true;
    },

    // 添加错误状态显示
    showErrorState(message) {
      this.hasError = true;
      this.errorMessage = message;
    },

    // 重新加载方法
    reload() {
      this.hasError = false;
      this.errorMessage = '';
      this.loadOrderItems();
      this.getDefaultAddress();
    },

    // 添加错误处理方法
    handleError(error, message) {
      console.error(error);
      this.hasError = true;
      this.errorMessage = message || '加载失败，请重试';
      this.isLoading = false;
    },

    // 设置选择的地址
    setAddress(address) {
      console.log('从地址选择页面接收到地址:', address);
      console.log('地址字段:', Object.keys(address).join(', '));
      console.log('地址省市区:', address.provinceName, address.cityName, address.districtName);
      
      if (address) {
        // 确保地址对象包含所有必要字段
        if (!address.provinceName && address.province) {
          address.provinceName = address.province;
        }
        if (!address.cityName && address.city) {
          address.cityName = address.city;
        }
        if (!address.districtName && address.district) {
          address.districtName = address.district;
        }
        
        this.address = address;
        
        // 保存地址到本地存储，以便刷新后仍能使用
        uni.setStorageSync('selectedAddress', address);
        
        // 显示成功信息
        uni.showToast({
          title: '已选择地址',
          icon: 'success',
          duration: 1500
        });
      }
    },

    cancelPayment() {
      this.closeQRCode();
    },

    confirmPayment() {
      if (!this.currentOrderId) return;
      
      uni.showLoading({
        title: '正在确认支付状态'
      });
      
      orderApi.checkPayStatus(this.currentOrderId)
        .then(res => {
          if (res.code === 200 && res.errorMessage === 'SUCCESS') {
            this.handlePaymentSuccess();
          } else {
            uni.showToast({
              title: '支付未完成',
              icon: 'none'
            });
          }
        })
        .catch(err => {
          console.error('确认支付失败:', err);
          uni.showToast({
            title: '确认支付失败',
            icon: 'none'
          });
        })
        .finally(() => {
          uni.hideLoading();
        });
    },

    // 修改关闭二维码方法
    closeQRCode() {
      uni.showModal({
        title: '提示',
        content: '确定要取消支付吗？',
        success: (res) => {
          if (res.confirm) {
            this.clearPaymentStatusPolling();
            this.showQRCode = false;
            this.qrCodeUrl = '';
            // 跳转到订单列表
            this.navigateToOrderList(this.currentOrderId);
          }
        }
      });
    },

    // Update handleOrderSubmitError method
    handleOrderSubmitError(error) {
      console.error('订单提交失败:', error);
      
      // Reset states
      this.loadingStates.submitting = false;
      this.errorStates.orderSubmit = true;
      
      // Hide loading
      uni.hideLoading();
      
      // Get error message
      let errorMessage = error.message || '创建订单失败';
      if (error.response) {
        switch (error.response.status) {
          case 401:
            errorMessage = '请先登录后再提交订单';
            break;
          case 400:
            errorMessage = error.response.data?.message || '订单数据有误，请检查';
            break;
          case 500:
            errorMessage = '服务器错误，请稍后重试';
            break;
        }
      }
      
      // Show error modal with retry option
      uni.showModal({
        title: '提交订单失败',
        content: `${errorMessage}${this.retryCount < this.maxRetries ? '\n是否重试？' : '\n请检查订单信息后重试'}`,
        confirmText: this.retryCount < this.maxRetries ? '重试' : '确定',
        showCancel: this.retryCount < this.maxRetries,
        success: (res) => {
          if (res.confirm && this.retryCount < this.maxRetries) {
            this.retryCount++;
            this.submitOrder();
          } else {
            this.retryCount = 0;
            this.errorStates.orderSubmit = false;
          }
        }
      });
    },

    // 跳转到订单列表
    navigateToOrderList(orderId) {
      const url = `/pages/order/order-list?status=PENDING_PAYMENT&highlight=${orderId}`;
      
      uni.redirectTo({
        url,
        success: () => {
          console.log('跳转到订单列表成功');
        },
        fail: (err) => {
          console.error('跳转到订单列表失败:', err);
          // 如果跳转失败，使用switchTab
          uni.switchTab({
            url: '/pages/user/user',
            success: () => {
              // 存储订单ID，以便在用户页面打开相应订单
              uni.setStorageSync('pendingOrderId', orderId);
            }
          });
        }
      });
    },
    
    // 修改 cleanupAfterOrder 方法中获取用户ID的部分
    async cleanupAfterOrder() {
      try {
        // 清除购物车中已选商品
        const selectedItemIds = this.orderItems
          .map(item => item.id)
          .filter(id => id);
          
        if (selectedItemIds.length > 0) {
          const userId = this.getUserIdentifier();
          if (userId) {
            await Promise.all(
              selectedItemIds.map(id => cartApi.deleteCartItem(id, userId))
            );
          }
        }
        
        // 清除临时数据
        uni.removeStorageSync('tempOrderItems');
        uni.removeStorageSync('checkoutItems');
      } catch (error) {
        console.error('清理数据失败:', error);
      }
    },

    // Add getFullAddress method
    getFullAddress() {
      if (!this.address) {
        console.error('地址对象为空');
        return '';
      }
      
      const { provinceName, cityName, districtName, detail } = this.address;
      
      // Log address components for debugging
      console.log('地址组件:', {
        provinceName,
        cityName,
        districtName,
        detail
      });
      
      if (!provinceName || !cityName || !districtName || !detail) {
        console.error('地址信息不完整');
        return '';
      }
      
      return `${provinceName}${cityName}${districtName}${detail}`.trim();
    },

    // 添加二维码图片加载事件处理
    handleQRCodeLoad(event) {
      console.log('二维码图片加载成功:', event);
    },

    clearPaymentStatusPolling() {
      if (this.paymentStatusTimer) {
        clearTimeout(this.paymentStatusTimer);
        this.paymentStatusTimer = null;
      }
    },

    // 修改二维码加载错误处理方法
    async handleQRCodeError(event) {
      console.log('二维码图片加载失败:', event);
      
      try {
        uni.showLoading({
          title: '重新获取二维码...',
          mask: true
        });
        
        // 重新获取支付二维码
        const payRes = await orderMedicineApi.payOrder({
          orderId: this.currentOrderId,
          paymentType: this.paymentOptions[this.selectedPayment].value,
          totalFee: Math.round(Number(this.actualPayment) * 100).toString()
        });
        
        if (payRes.code === 200 && payRes.data) {
          this.outTradeNo = payRes.data.outTradeNo;
          this.qrCodeUrl = payRes.data.qrCodeImage;
          
          // 重新开始检查支付状态
          this.startPaymentStatusCheck();
        } else {
          throw new Error(payRes.msg || '获取支付二维码失败');
        }
      } catch (error) {
        console.error('重新获取二维码失败:', error);
        uni.showModal({
          title: '获取二维码失败',
          content: '是否重试？',
          confirmText: '重试',
          cancelText: '取消',
          success: (res) => {
            if (res.confirm) {
              this.handleQRCodeError(event);
            } else {
              this.closeQRCode();
            }
          }
        });
      } finally {
        uni.hideLoading();
      }
    },
  }
}
</script>

<style lang="scss">
.order-confirm {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 120rpx;
  
  .address-section {
    background-color: #fff;
    padding: 30rpx;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
    position: relative;
    
    &::after {
      content: '';
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      height: 6rpx;
      background: linear-gradient(to right, #ff9500, #ff5500);
      transform: scaleY(0.5);
    }
    
    .address-info {
      flex: 1;
      
      .user-info {
        margin-bottom: 10rpx;
        
        .name {
          font-size: 32rpx;
          color: #333;
          font-weight: bold;
          margin-right: 20rpx;
        }
        
        .phone {
          font-size: 28rpx;
          color: #666;
        }
      }
      
      .address-detail {
        display: flex;
        align-items: center;
        
        .tag {
          font-size: 22rpx;
          color: #ff5500;
          background-color: rgba(255, 85, 0, 0.1);
          padding: 4rpx 12rpx;
          border-radius: 4rpx;
          margin-right: 10rpx;
        }
        
        .detail {
          font-size: 28rpx;
          color: #333;
          line-height: 1.4;
        }
      }
    }
    
    .no-address {
      width: 100%;
      padding: 30rpx;
      text-align: center;
      
      .add-address-btn {
        width: 80%;
        height: 80rpx;
        line-height: 80rpx;
        background: linear-gradient(to right, #ff7500, #ff5500);
        color: #fff;
        font-size: 28rpx;
        border-radius: 40rpx;
        border: none;
        margin: 0 auto;
        
        &::after {
          border: none;
        }
      }
    }
    
    .arrow {
      font-size: 32rpx;
      color: #999;
      margin-left: 20rpx;
    }
  }
  
  .medicine-list {
    background-color: #fff;
    margin-bottom: 20rpx;
    
    .list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
      
      .header-left {
        display: flex;
        align-items: center;
        
        text {
          font-size: 28rpx;
          color: #333;
          font-weight: bold;
        }
        
        .total-count {
          font-size: 24rpx;
          color: #666;
          font-weight: normal;
          margin-left: 15rpx;
        }
      }
      
      .specification {
        font-size: 24rpx;
        color: #999;
        font-weight: normal;
      }
    }
    
    .medicine-item {
      display: flex;
      padding: 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .medicine-image {
        width: 160rpx;
        height: 160rpx;
        border-radius: 8rpx;
        margin-right: 20rpx;
      }
      
      .medicine-info {
        flex: 1;
        
        .medicine-name {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 10rpx;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
        }
        
        .medicine-details {
          display: flex;
          flex-wrap: wrap;
          margin-bottom: 20rpx;
          
          .medicine-spec, .medicine-dosage {
            font-size: 24rpx;
            color: #999;
            margin-right: 20rpx;
          }
        }
        
        .price-quantity {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .price {
            font-size: 32rpx;
            color: #ff5500;
            font-weight: bold;
          }
          
          .item-quantity {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            
            .quantity {
              font-size: 28rpx;
              color: #999;
              margin-bottom: 6rpx;
            }
            
            .item-total {
              font-size: 24rpx;
              color: #666;
            }
          }
        }
      }
    }
  }
  
  .delivery-section {
    background-color: #fff;
    margin-bottom: 20rpx;
    
    .section-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .label {
        font-size: 28rpx;
        color: #333;
      }
      
      .value {
        font-size: 28rpx;
        color: #666;
      }
    }
  }
  
  .payment-section {
    background-color: #fff;
    margin-bottom: 20rpx;
    
    .section-header {
      padding: 20rpx 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
      
      text {
        font-size: 28rpx;
        color: #333;
        font-weight: bold;
      }
    }
    
    .payment-options {
      .payment-option {
        display: flex;
        align-items: center;
        padding: 30rpx;
        border-bottom: 1rpx solid #f5f5f5;
        
        &:last-child {
          border-bottom: none;
        }
        
        &.active {
          background-color: #f8f8f8;
          border-left: 8rpx solid #ff5500;
        }
        
        .payment-icon {
          width: 56rpx;
          height: 56rpx;
          margin-right: 20rpx;
        }
        
        .payment-name {
          flex: 1;
          font-size: 28rpx;
          color: #333;
        }
        
        .checkbox {
          width: 40rpx;
          height: 40rpx;
          border-radius: 50%;
          border: 2rpx solid #ddd;
          
          &.checked {
            background-color: #ff5500;
            border-color: #ff5500;
            position: relative;
            
            &::after {
              content: '';
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%) rotate(-45deg);
              width: 20rpx;
              height: 10rpx;
              border-left: 4rpx solid #fff;
              border-bottom: 4rpx solid #fff;
            }
          }
        }
      }
    }
  }
  
  .price-section {
    background-color: #fff;
    padding: 0 30rpx;
    margin-bottom: 15rpx;
    
    .price-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f5f5f5;
      
      .label {
        font-size: 28rpx;
        color: #333;
      }
      
      .value {
        font-size: 28rpx;
        color: #333;
      }
      
      &.total {
        padding: 30rpx 0;
        
        .label {
          font-size: 30rpx;
          font-weight: bold;
        }
        
        .value {
          font-size: 36rpx;
          color: #ff5500;
          font-weight: bold;
        }
      }
    }
  }
  
  .pay-bar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    height: 100rpx;
    background-color: #fff;
    display: flex;
    align-items: center;
    padding-left: 30rpx;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .total-price {
      flex: 1;
      font-size: 28rpx;
      color: #333;
      
      .price {
        font-size: 36rpx;
        color: #ff5500;
        font-weight: bold;
      }
    }
    
    .pay-btn {
      width: 240rpx;
      height: 100rpx;
      line-height: 100rpx;
      background-color: #ff5500;
      color: #fff;
      font-size: 32rpx;
      text-align: center;
      border-radius: 0;
      
      &.loading {
        background-color: #ff8855;
        opacity: 0.8;
      }
      
      &:disabled {
        background-color: #ccc;
        color: #fff;
      }
    }
  }

  // 添加加载状态样式
  .loading-state {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #fff;
    
    text {
      font-size: 28rpx;
      color: #666;
    }
  }
  
  // 添加错误状态样式
  .error-state {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #fff;
    padding: 30rpx;
    
    text {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 30rpx;
      text-align: center;
    }
    
    .reload-btn {
      width: 200rpx;
      height: 80rpx;
      line-height: 80rpx;
      background: #ff5500;
      color: #fff;
      font-size: 28rpx;
      border-radius: 40rpx;
    }
  }

  /* 调试工具样式 */
  .debug-section {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: rgba(255, 255, 255, 0.95);
    padding: 20rpx;
    border-top: 2rpx solid #ddd;
    z-index: 999;
    max-height: 50vh;
    overflow-y: auto;
    
    .debug-title {
      font-size: 28rpx;
      color: #333;
      text-align: center;
      margin-bottom: 20rpx;
      font-weight: bold;
    }
    
    .debug-buttons {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      
      .debug-btn {
        width: 48%;
        height: 70rpx;
        line-height: 70rpx;
        margin-bottom: 15rpx;
        font-size: 24rpx;
        background-color: #4CAF50;
        color: white;
        border: none;
        border-radius: 8rpx;
        
        &.alt {
          background-color: #FF9800;
        }
        
        &.danger {
          background-color: #f44336;
        }
        
        &::after {
          border: none;
        }
      }
    }
  }

  /* 更新二维码弹窗样式 */
  .qrcode-popup-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }

  .qrcode-popup {
    background: #fff;
    border-radius: 12rpx;
    width: 600rpx;
    padding: 30rpx;

    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;
      padding-bottom: 20rpx;
      border-bottom: 1px solid #eee;

      .popup-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }

      .close-btn {
        font-size: 48rpx;
        color: #999;
        padding: 0 20rpx;
        line-height: 1;
        cursor: pointer;

        &:active {
          opacity: 0.7;
        }
      }
    }

    .qrcode-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20rpx 0;

      .loading-wrapper {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 320rpx;
        
        .loading {
          font-size: 28rpx;
          color: #666;
        }
      }
      
      .qrcode-wrapper {
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .qrcode-image {
          width: 320rpx;
          height: 320rpx;
          background-color: #fff;
          border: 1px solid #eee;
          border-radius: 8rpx;
        }
        
        .price {
          margin-top: 20rpx;
          font-size: 36rpx;
          color: #ff4d4f;
          font-weight: bold;
        }
      }
    }

    .qrcode-footer {
      text-align: center;
      margin-top: 30rpx;
      
      .tip {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 10rpx;
      }
      
      .order-number {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 20rpx;
      }
    }

    .qrcode-buttons {
      display: flex;
      justify-content: space-between;
      margin-top: 30rpx;
      
      .qr-btn {
        width: 45%;
        height: 80rpx;
        line-height: 80rpx;
        border-radius: 40rpx;
        font-size: 28rpx;
        
        &.cancel {
          background-color: #f5f5f5;
          color: #666;
        }
        
        &.confirm {
          background-color: #ff5500;
          color: #fff;
        }
      }
    }
  }
}
</style> 